package com.sinping.qh.service.app.lab.impl;

import com.google.common.collect.Lists;
import com.sinping.qh.api.support.*;
import com.sinping.qh.domain.auth.Role;
import com.sinping.qh.domain.common.UnitDomain;
import com.sinping.qh.domain.lab.LabInspectItemRelationDomain;
import com.sinping.qh.domain.lab.LabInspectItemTreeDomain;
import com.sinping.qh.domain.lab.LaboratoryDomain;
import com.sinping.qh.domain.user.UserLaboratory;
import com.sinping.qh.dto.admin.ApiUnitDto;
import com.sinping.qh.dto.admin.lab.InspectItemHiddenDangerDto;
import com.sinping.qh.dto.admin.lab.LabInspectItemRelationDto;
import com.sinping.qh.dto.admin.lab.LaboratoryByAppDto;
import com.sinping.qh.dto.admin.lab.LaboratoryDto;
import com.sinping.qh.dto.app.lab.LaboratoryByAppDTO;
import com.sinping.qh.dto.app.user.UserLaboratoryDTO;
import com.sinping.qh.dto.app.user.UserLaboratoryGroupDTO;
import com.sinping.qh.dto.mongo.auth.UserSessionDTO;
import com.sinping.qh.query.base.AggregateOperator;
import com.sinping.qh.query.base.AggregateParams;
import com.sinping.qh.query.lab.LabInspectItemTreeQuery;
import com.sinping.qh.query.lab.LaboratoryQuery;
import com.sinping.qh.query.lab.UnitQuery;
import com.sinping.qh.query.lab.UserLaboratoryQuery;
import com.sinping.qh.repository.mongo.UnitRepository;
import com.sinping.qh.repository.mongo.lab.LabInspectItemRelationRepository;
import com.sinping.qh.repository.mongo.lab.LabInspectItemTreeRepository;
import com.sinping.qh.repository.mongo.lab.LaboratoryRepository;
import com.sinping.qh.repository.mongo.lab.impl.LabRepositoryImpl;
import com.sinping.qh.repository.mongo.user.UserLaboratoryRepository;
import com.sinping.qh.service.MongoManager;
import com.sinping.qh.service.admin.impl.LaboratoryServiceImpl;
import com.sinping.qh.service.app.lab.ILaboratoryByAppService;
import com.sinping.qh.service.auth.IRoleService;
import com.sinping.qh.service.common.CommonDbConst;
import com.sinping.qh.utils.mapper.BeanMapper;
import com.sinping.qh.utils.mapper.JsonMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author jiahuaiqing
 * @create 2018/6/9
 */
@Service
public class LaboratoryByAppServiceImpl implements ILaboratoryByAppService {

    @Autowired
    MongoManager mongoManager;

    @Autowired
    LabInspectItemRelationRepository labInspectItemRelationRepository;

    @Autowired
    UserLaboratoryRepository userLaboratoryRepository;

    @Autowired
    LaboratoryRepository laboratoryRepository;

    @Autowired
    UnitRepository unitRepository;

    @Autowired
    LabRepositoryImpl labRepositoryImpl;

    @Autowired
    LabInspectItemTreeRepository labInspectItemTreeRepository;

    @Autowired
    LaboratoryServiceImpl laboratoryService;

    @Autowired
    private IRoleService roleService;

    /**
     * 查询用户负责的院系
     *
     * @param frontPage
     * @return
     */
    @Override
    public FrontPage findPage(FrontPage frontPage) {

        Sort sort;
        if (StringUtils.isNotBlank(frontPage.getProp()) &&
                StringUtils.isNotBlank(frontPage.getOrder())) {
            sort = new Sort(Sort.Direction.fromString(frontPage.getOrder()), frontPage.getProp());

        } else {
            sort = new Sort(Sort.Direction.DESC, "gmt_created");
        }
        //查询条件
        UserLaboratoryQuery userLaboratoryQuery = new UserLaboratoryQuery();
        userLaboratoryQuery.setStatus(CommonDbConst.DB_DELETE_NORMAL);
        PageRequest page = new PageRequest(frontPage.getPage() - 1, frontPage.getSize(), sort);
        Page<UserLaboratory> userLaboratoryPages = mongoManager.findPage(userLaboratoryQuery, page, UserLaboratory.class);

        ResDtoUtil.defaultUtil().pageDomainDtoToFrontDto(userLaboratoryPages, UserLaboratoryDTO.class, frontPage);
        return frontPage;
    }

    /**
     * 根据用户id查询所负责的院系(没有加权限且和加权限的实现方式不一样)
     * 参考了CheckRecordServiceImpl$findPageByUniting 的分组查询
     *
     * @param frontPage
     * @param userSessionDTO
     * @return
     */
    @Deprecated
    @Override
    public FrontPage findPageByUserid(FrontPage frontPage, UserSessionDTO userSessionDTO) {
        Sort sort;
        if (StringUtils.isNotBlank(frontPage.getProp()) &&
                StringUtils.isNotBlank(frontPage.getOrder())) {
            sort = new Sort(Sort.Direction.fromString(frontPage.getOrder()), frontPage.getProp());
        } else {
            sort = new Sort(Sort.Direction.DESC, "gmt_created");
        }

        Map<String, Object> condition = frontPage.getCondition();
        String user_id = (String) condition.get("user_id");

        //查询条件
        PageRequest page = new PageRequest(frontPage.getPage() - 1, frontPage.getSize(), sort);

        //分组条件
        List<String> groupParams = Lists.newArrayList("manager_unit_id", "manager_unit_name");
        AggregateParams aggregateParams = new AggregateParams();
        //统计数量
        aggregateParams.add("manager_lab_id", "managerLabIdCount", AggregateOperator.count);

        List<UserLaboratoryGroupDTO> rs = labRepositoryImpl.findPageByUserId(user_id, groupParams, page, aggregateParams, UserLaboratory.class, UserLaboratoryGroupDTO.class);

        List<UserLaboratoryGroupDTO> rsByNoPage = labRepositoryImpl.findPageByUserId(user_id, groupParams, null, aggregateParams, UserLaboratory.class, UserLaboratoryGroupDTO.class);


        Page<UserLaboratoryGroupDTO> pages = new PageImpl<>(rs, page, rsByNoPage.size());
        frontPage = ResDtoUtil.defaultUtil().pageDomainDtoToFrontDto(pages, UserLaboratoryGroupDTO.class, frontPage);
        return frontPage;

    }


    @Override
    public FrontPage findPageByUseridAddQuanxian(FrontPage frontPage, UserSessionDTO userSessionDTO) {
        Sort sort;
        if (StringUtils.isNotBlank(frontPage.getProp()) &&
                StringUtils.isNotBlank(frontPage.getOrder())) {
            sort = new Sort(Sort.Direction.fromString(frontPage.getOrder()), frontPage.getProp());
        } else {
            sort = new Sort(Sort.Direction.ASC, "unit_name");
        }


        Map<String, Object> condition = frontPage.getCondition();
        String user_id = (String) condition.get("user_id");

        List<String> unitIDList = new ArrayList<>();
        List<ApiUnitDto> userManagerLabInUnit = getUserManagerLabInUnit(user_id);
        for (ApiUnitDto unitdto : userManagerLabInUnit) {
            unitIDList.add(unitdto.getId());
        }

        UnitQuery unitQuery = new UnitQuery();
        unitQuery.setUnitIDList(unitIDList);

        //查询条件
        PageRequest page = new PageRequest(frontPage.getPage() - 1, frontPage.getSize(), sort);
        Page<UnitDomain> pages = mongoManager.findPage(unitQuery, page, UnitDomain.class);

        frontPage = ResDtoUtil.defaultUtil().pageDomainDtoToFrontDto(pages, ApiUnitDto.class, frontPage);
        return frontPage;
    }


    /**
     * 根据院系id,获取用户负责的实验室列表
     *
     * @param frontPage
     * @param userSessionDTO
     * @return
     */
    @Deprecated
    @Override
    public FrontPage findPageByUnitid(FrontPage frontPage, UserSessionDTO userSessionDTO) {
        Sort sort;
        if (StringUtils.isNotBlank(frontPage.getProp()) &&
                StringUtils.isNotBlank(frontPage.getOrder())) {
            sort = new Sort(Sort.Direction.fromString(frontPage.getOrder()), frontPage.getProp());
        } else {
            sort = new Sort(Sort.Direction.DESC, "gmt_created");
        }

        Map<String, Object> condition = frontPage.getCondition();
        String manager_unit_id = (String) condition.get("manager_unit_id");

        //查询条件
        PageRequest page = new PageRequest(frontPage.getPage() - 1, frontPage.getSize(), sort);
        //分组条件
//        List<String> groupParams = Lists.newArrayList("manager_lab_id","manager_lab_name");
//        AggregateParams aggregateParams = new AggregateParams();

        List<LaboratoryByAppDto> rs = labRepositoryImpl.findPageByUnitId(manager_unit_id, userSessionDTO.getUserInfo().getId(), page, UserLaboratory.class, LaboratoryByAppDto.class);

        List<LaboratoryByAppDto> rsByNoPage = labRepositoryImpl.findPageByUnitId(manager_unit_id, userSessionDTO.getUserInfo().getId(), null, UserLaboratory.class, LaboratoryByAppDto.class);

        Page<LaboratoryByAppDto> pages = new PageImpl<>(rs, page, rsByNoPage.size());
        frontPage = ResDtoUtil.defaultUtil().pageDomainDtoToFrontDto(pages, LaboratoryByAppDto.class, frontPage);
        return frontPage;
    }

    @Override
    public FrontPage findPageByUnitidAddQuanxian(FrontPage frontPage, UserSessionDTO userSessionDTO) {
        //拿到负责的院系id,直接调用后台的接口就可以
        Map<String, Object> condition = frontPage.getCondition();
        //String unit_id = (String) condition.get("unit_id");

        //配置负责实验室
        List<LaboratoryDto> laboratoryDto = laboratoryService.userManagerLabConfig(userSessionDTO.getUserInfo().getId(),frontPage);
        //配置负责院系(除去配置负责实验室的)
        List<LaboratoryDto> laboratoryDtos_unit = laboratoryService.userManagerUnitConfig(userSessionDTO.getUserInfo().getId(),frontPage);

        List<String> allLabId = new ArrayList<>();
        if (null != laboratoryDto && laboratoryDto.size() > 0) {
            for (int i = 0; i < laboratoryDto.size(); i++) {
                allLabId.add(laboratoryDto.get(i).getId());
            }
        }

        if (null != laboratoryDtos_unit && laboratoryDtos_unit.size() > 0) {
            if (allLabId.size() > 0) {
                for (int i = 0; i < laboratoryDtos_unit.size(); i++) {
                    if (!allLabId.contains(laboratoryDtos_unit.get(i).getId())) {
                        allLabId.add(laboratoryDtos_unit.get(i).getId());
                    }
                }
            } else {
                for (int i = 0; i < laboratoryDtos_unit.size(); i++) {
                    allLabId.add(laboratoryDtos_unit.get(i).getId());
                }
            }
        }

        Integer pageSize = frontPage.getSize();
        Integer pageNum = frontPage.getPage();

        LaboratoryQuery query;
        Map<String, Object> conditionMap = frontPage.getCondition();
        if (null == conditionMap || conditionMap.isEmpty()) {
            //查询全部数据
            query = new LaboratoryQuery();
        } else {
            //按条件查询
            String conditionMapJson = JsonMapper.defaultMapper().toJson(conditionMap);
            LaboratoryDto laboratory_Dto = JsonMapper.defaultMapper().fromJson(conditionMapJson, LaboratoryDto.class);
            query = BeanMapper.map(laboratory_Dto, LaboratoryQuery.class);
        }

        //设置查询出来的labid
        query.setLabIDList(allLabId);

        try{
            Pageable pageable = new PageRequest(pageNum - 1, pageSize, new Sort(Sort.Direction.DESC, "gmt_created"));
            Page<LaboratoryDomain> laboratoryListPage = mongoManager.findPage(query, pageable, LaboratoryDomain.class);

            List<LaboratoryDto> laboratoryDtoList = BeanMapper.mapList(laboratoryListPage.getContent(), LaboratoryDto.class);

            //增加安全员和安全员电话
            UserLaboratoryQuery userLaboratoryQuery = new UserLaboratoryQuery();
            userLaboratoryQuery.setType(CommonDbConst.USER_MANAGER_LAB);
            List<UserLaboratory> userLaboratories = mongoManager.find(userLaboratoryQuery, UserLaboratory.class);
            for (LaboratoryDto laboratorydto : laboratoryDtoList) {
                StringBuffer security = new StringBuffer();
                StringBuffer telephone = new StringBuffer();
                for (int i = 0; i < userLaboratories.size(); i++) {
                    if (userLaboratories.get(i).getManagerLabId().equals(laboratorydto.getId())) {
                        if (!StringUtils.isEmpty(userLaboratories.get(i).getRoleId())) {
                            Role role = roleService.selectById(userLaboratories.get(i).getRoleId());
                            if (role != null) {
                                if (CommonDbConst.SECURITY_YES.equals(role.getSecurity())) {
                                    if (userLaboratories.size() == 1) {
                                        security.append(userLaboratories.get(i).getUserName());
                                        telephone.append(userLaboratories.get(i).getTelephone());
                                    } else {
                                        if (security.toString().length() == 0) {
                                            security.append(userLaboratories.get(i).getUserName());
                                            telephone.append(userLaboratories.get(i).getTelephone());
                                        } else {
                                            security.append("," + userLaboratories.get(i).getUserName());
                                            telephone.append("," + userLaboratories.get(i).getTelephone());
                                        }

                                    }
                                }
                            }
                        }


                    }
                }
                laboratorydto.setSecurity(security.toString());
                laboratorydto.setSecurityPhone(telephone.toString());
            }

            frontPage = ResDtoUtil.defaultUtil().pageDomainDtoToFrontDto(laboratoryListPage, LaboratoryDto.class, frontPage);
//            ResDto resDto = new ResDto(ConstEum.SUCCESS);
//            resDto.setMsg("成功");
//            long totalPages = laboratoryListPage.getTotalPages();
//            int currentPage = frontpage.getPage();
//            frontpage = new FrontPage();
//            frontpage.setPage(currentPage);
//            frontpage.setTotal((int) laboratoryListPage.getTotalElements());
//            frontpage.setPages((int) totalPages);
//            frontpage.setRecords(laboratoryDtoList);
//            resDto.setDatas(JsonMapper.defaultMapper().toJson(frontpage));

//            ResDtoUtil.defaultUtil().pageDomainDtoToFrontDto(resDto, laboratoryDomainPage, LaboratoryDto.class, frontpage);
            return frontPage;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }


    @Override
    public List<UserLaboratoryDTO> getUserLaboratory(UserSessionDTO userSessionDTO) {

        List<UserLaboratory> userLaboratoryList =
                userLaboratoryRepository.findAllByUserIdAndTypeOrderByGmtCreatedDesc(userSessionDTO.getUserInfo().getId(), "0");

        List<UserLaboratoryDTO> userLaboratoryDTOList = new ArrayList<>();
        UserLaboratoryDTO userLaboratoryDTO;

        for (UserLaboratory userLaboratory : userLaboratoryList) {

            userLaboratoryDTO = BeanMapper.map(userLaboratory, UserLaboratoryDTO.class);

            userLaboratoryDTOList.add(userLaboratoryDTO);

        }
        return userLaboratoryDTOList;
    }

    @Override
    public List<LaboratoryByAppDTO> getUserBuildingByUnit(String unit_id, UserSessionDTO userSessionDTO) {

        List<LaboratoryDomain> laboratoryDomainList =
                laboratoryRepository.findLaboratoryDomainByUnitIdAndStatus(unit_id, CommonDbConst.DB_DELETE_NORMAL);

        List<LaboratoryByAppDTO> laboratoryByAppDTOList = new ArrayList<>();

        //找出不同的楼宇id

        HashMap<String, String> buildingIdList = new HashMap<>();

        for (LaboratoryDomain laboratoryDomain : laboratoryDomainList) {

            if (StringUtils.isNotBlank(laboratoryDomain.getBuildingId()) && !buildingIdList.containsKey(laboratoryDomain.getBuildingId())) {
                LaboratoryByAppDTO laboratoryByAppDTO = BeanMapper.map(laboratoryDomain, LaboratoryByAppDTO.class);
                laboratoryByAppDTOList.add(laboratoryByAppDTO);
                buildingIdList.put(laboratoryDomain.getBuildingId(), laboratoryDomain.getBuildingId());
            }

        }
        return laboratoryByAppDTOList;
    }

    /**
     * 根据实验室id,获取已经配置的检查项
     *
     * @param labId
     * @return
     */
    @Override
    public ResDto getConfigedInsepctItemByLabId(String labId) {
        try {
            List<LabInspectItemRelationDomain> byLabId = labInspectItemRelationRepository.findByLabId(labId);
            if (byLabId == null || byLabId.size() == 0) {
                return new ResDto(Const.SUCCESS, "");
            }
            List<LabInspectItemRelationDto> labInspectItemRelationDtos = BeanMapper.mapList(byLabId, LabInspectItemRelationDto.class);
            String labInspectItemDtosStr = JsonMapper.defaultMapper().toJson(labInspectItemRelationDtos);
            ResDto resDto = new ResDto(ConstEum.SUCCESS);
            resDto.setDatas(labInspectItemDtosStr);
            return resDto;
        } catch (Exception e) {
            e.printStackTrace();
            return new ResDto(Const.SERVER_ERROR, "获取已经配置的检查项数据异常");
        }

    }

    //取消配置
    @Override
    public ResDto cancleLabInspectItemById(LabInspectItemRelationDto labInspectItemRelationDto) {
        try {
            LabInspectItemRelationDomain one = labInspectItemRelationRepository.findByLabIdAndInspectItemId(labInspectItemRelationDto.getLabId(), labInspectItemRelationDto.getInspectItemId());
            if (one == null) {
                return new ResDto(Const.SERVER_ERROR, "已经取消配置了");
            }
            labInspectItemRelationRepository.delete(one);
            ResDto resDto = new ResDto(ConstEum.SUCCESS);
            resDto.setMsg("删除成功");
            resDto.setDatas("");
            return resDto;
        } catch (Exception e) {
            e.printStackTrace();
            return new ResDto(Const.SERVER_ERROR, "删除异常");
        }
    }


    @Override
    public ResDto getLabInspectItemDescRelation(String itemSubcategory, String lab_id) {
        try {

            List<InspectItemHiddenDangerDto> yuanxiAndLabList = getListData(itemSubcategory, lab_id);

            String labInspectItemDtosStr = JsonMapper.defaultMapper().toJson(yuanxiAndLabList);
            ResDto resDto = new ResDto(ConstEum.SUCCESS);
            resDto.setDatas(labInspectItemDtosStr);
            return resDto;
        } catch (Exception e) {
            e.printStackTrace();
            return new ResDto(Const.SERVER_ERROR, "获取实验室检查项的隐患记录异常！");
        }
    }

    /**
     * 获取综合和实验室的隐患记录（用于离线检查计划的数据）
     * @param itemSubcategory
     * @param lab_id
     * @return
     */
    public List<InspectItemHiddenDangerDto> getListData(String itemSubcategory, String lab_id){
        List<InspectItemHiddenDangerDto> weixianyuanList = null;
        if (StringUtils.isNotBlank(lab_id)) {
            weixianyuanList = getWeixianYuanList(lab_id);
        }

        List<InspectItemHiddenDangerDto> yuanxiAndLabList = getLabDangerByitemSubcategory(itemSubcategory);
        if (null != weixianyuanList && weixianyuanList.size() > 0) {
            yuanxiAndLabList.addAll(weixianyuanList);
        }

        return yuanxiAndLabList;
    }

    /**
     * 根据lab_id来查出，已经配置危险源隐患
     *
     * @param lab_id
     * @return
     */
    private List<InspectItemHiddenDangerDto> getWeixianYuanList(String lab_id) {
        //实验室检查项关系表中查：byLabId注意是一级和二级检查项的id集合
        List<LabInspectItemRelationDomain> byLabId = labInspectItemRelationRepository.findByLabId(lab_id);
        List<InspectItemHiddenDangerDto> weixianyuanList = null;
        if (byLabId != null && byLabId.size() > 0) {
            weixianyuanList = getLabDangerByitemSubcategory(byLabId);
        }
        return weixianyuanList;
    }

    /**
     * 根据分类来查出--院系级和实验室级的检查项
     *
     * @param item_subcategory
     * @return
     */
    private List<InspectItemHiddenDangerDto> getLabDangerByitemSubcategory(String item_subcategory) {
        LabInspectItemTreeQuery labInspectItemTreeQuery = new LabInspectItemTreeQuery();
        //先查询全部危险源隐患列表,再取一级，再取二级...(好处是只查询一次库)
        labInspectItemTreeQuery.setItemSubcategory(item_subcategory);
        labInspectItemTreeQuery.setStatus("0");

        List<LabInspectItemTreeDomain> labInspectItemDomains = mongoManager.find(labInspectItemTreeQuery, LabInspectItemTreeDomain.class);
        List<InspectItemHiddenDangerDto> treeByInspectItem = null;
        if (null != labInspectItemDomains && labInspectItemDomains.size() > 0) {
            treeByInspectItem = this.createTreeByInspectItemAndSubcategory(labInspectItemDomains);
        }
        //List<LabInspectItemTreeDto> labInspectItemDtos = BeanMapper.mapList(labInspectItemDomains, LabInspectItemTreeDto.class);
        //String labInspectItemDtosStr = JsonMapper.defaultMapper().toJson(treeByInspectItem);
        return treeByInspectItem;
    }

    /**
     * 根据已经配置的检查项id--查出已经配置检查项的所有信息
     *
     * @param byLabId 一定注意了 byLabId是一级的id集合,byLabIdOther 二级的id
     * @return
     */
    private List<InspectItemHiddenDangerDto> getLabDangerByitemSubcategory(List<LabInspectItemRelationDomain> byLabId) {
        LabInspectItemTreeQuery labInspectItemTreeQuery = new LabInspectItemTreeQuery();
        //先查询全部危险源隐患列表,再取一级，再取二级...(好处是只查询一次库)
        labInspectItemTreeQuery.setItemSubcategory("2");
        labInspectItemTreeQuery.setStatus("0");

        List<LabInspectItemTreeDomain> labInspectItemDomains = mongoManager.find(labInspectItemTreeQuery, LabInspectItemTreeDomain.class, new Sort(Sort.Direction.DESC, "item_order"));
        List<InspectItemHiddenDangerDto> treeByInspectItem = null;
        if (null != labInspectItemDomains && labInspectItemDomains.size() > 0) {
            treeByInspectItem = this.createTreeByInspectItemAndSubcategory(labInspectItemDomains, byLabId);
        }
        return treeByInspectItem;
    }


    /**
     * 查出来的是一级二级和三级(只查ItemSubcategory为 0 和 1的数据)
     *
     * @param domainList
     * @return
     */
    public List<InspectItemHiddenDangerDto> createTreeByInspectItemAndSubcategory(List<LabInspectItemTreeDomain> domainList) {
        List<InspectItemHiddenDangerDto> dtoList = new ArrayList<>();
        for (LabInspectItemTreeDomain domain : domainList) {
            if (domain.getItemLevel().equals("1") && domain.getItemSubcategory().equals("0")) {
                InspectItemHiddenDangerDto dto = new InspectItemHiddenDangerDto();
                dto.setItemName(domain.getItemName());
                dto.setId(domain.getId());
                dto.setItemLevel(domain.getItemLevel());
                dto.setChildCount(domain.getChildCount());
                dto.setItemCategory(domain.getItemCategory());
                dto.setItemSubcategory(domain.getItemSubcategory());
                dto.setStatus(domain.getStatus());
                dto.setItemParentId(domain.getItemParentId());
                dto.setItemLevel(domain.getItemLevel());
                dtoList.add(dto);
                createTreeBy(dto, domainList);

            } else if (domain.getItemLevel().equals("1") && domain.getItemSubcategory().equals("1")) {
                InspectItemHiddenDangerDto dto = new InspectItemHiddenDangerDto();
                dto.setId(domain.getId());
                dto.setItemName(domain.getItemName());
                dto.setItemLevel(domain.getItemLevel());
                dto.setChildCount(domain.getChildCount());
                dto.setItemCategory(domain.getItemCategory());
                dto.setItemSubcategory(domain.getItemSubcategory());
                dto.setStatus(domain.getStatus());
                dto.setItemParentId(domain.getItemParentId());
                dto.setItemLevel(domain.getItemLevel());
                dtoList.add(dto);
                createTreeBy(dto, domainList);
            }
        }
        return dtoList;
    }


    public List<InspectItemHiddenDangerDto> createTreeByInspectItemAndSubcategory(List<LabInspectItemTreeDomain> domainList, List<LabInspectItemRelationDomain> byLabId) {
        //一级检查项id集合
        List<String> byLabIdOne = new ArrayList<>();
        //不是一级的检查项id集合
        List<String> byLabIdOther = new ArrayList<>();
        for (LabInspectItemRelationDomain labInspectItemRelationDomain :byLabId) {
            String inspectItemIdTwo = labInspectItemRelationDomain.getInspectItemId();
            //查询检查项的id
            LabInspectItemTreeDomain two = labInspectItemTreeRepository.findOne(inspectItemIdTwo);
            if (two.getItemLevel().equals("1") &&
                    !(byLabIdOne.contains(two.getId()))) {
                byLabIdOne.add(two.getId());
            }
            if (!two.getItemLevel().equals("1") &&
                    !(byLabIdOne.contains(two.getId()))) {
                byLabIdOther.add(two.getId());
            }
        }

        List<InspectItemHiddenDangerDto> dtoList = new ArrayList<>();
        for (LabInspectItemTreeDomain domain : domainList) {
            //查出一级危险源隐患并且一级id是已经配置的
            if (domain.getItemLevel().equals("1") && byLabIdOne.contains(domain.getId())) {

                InspectItemHiddenDangerDto dto = new InspectItemHiddenDangerDto();
                dto.setId(domain.getId());
                dto.setChildCount(domain.getChildCount());
                dto.setItemName(domain.getItemName());
                dto.setItemCategory(domain.getItemCategory());
                dto.setItemSubcategory(domain.getItemSubcategory());
                dto.setStatus(domain.getStatus());
                dto.setItemParentId(domain.getItemParentId());
                dto.setItemLevel(domain.getItemLevel());
                dtoList.add(dto);

                createTreeBy(dto, domainList, byLabIdOther);
            }
        }
        return dtoList;
    }

    /**
     * 已经配置的检查项（二级和三级） 注意：byLabIdOther 二级的id
     *
     * @param inspectItemHiddendto
     * @param domainList
     * @param byLabIdOther
     */
    private void createTreeBy(InspectItemHiddenDangerDto inspectItemHiddendto, List<LabInspectItemTreeDomain> domainList, List<String> byLabIdOther) {
        for (LabInspectItemTreeDomain domain : domainList) {
            //这里选择二级和三级
            if (domain.getItemLevel() != null && !domain.getItemLevel().equals("1") && inspectItemHiddendto.getId().equals(domain.getItemParentId())) {
                //检查项的id必须是在已经配置的集合中的
                if (byLabIdOther.contains(domain.getId())) {
                    List<InspectItemHiddenDangerDto> childrenList = inspectItemHiddendto.getChildDtoList();
                    if (childrenList == null) {
                        childrenList = new ArrayList<>();
                    }

                    InspectItemHiddenDangerDto dto2 = new InspectItemHiddenDangerDto();
                    dto2.setId(domain.getId());
                    dto2.setChildCount(domain.getChildCount());
                    dto2.setItemName(domain.getItemName());
                    dto2.setItemCategory(domain.getItemCategory());
                    dto2.setItemSubcategory(domain.getItemSubcategory());
                    dto2.setStatus(domain.getStatus());
                    dto2.setItemLevel(domain.getItemLevel());
                    dto2.setItemParentId(domain.getItemParentId());
                    dto2.setItemLevel(domain.getItemLevel());

                    childrenList.add(dto2);
                    inspectItemHiddendto.setChildDtoList(childrenList);

                    //递归
                    createTreeBy(dto2, domainList);

                }

            }
        }
    }

    /**
     * 所有检查项（二级和三级）
     *
     * @param inspectItemHiddendto
     * @param domainList
     */
    private void createTreeBy(InspectItemHiddenDangerDto inspectItemHiddendto, List<LabInspectItemTreeDomain> domainList) {
        for (LabInspectItemTreeDomain domain : domainList) {
            //这里选择二级和三级
            if (domain.getItemLevel() != null && !domain.getItemLevel().equals("1") && inspectItemHiddendto.getId().equals(domain.getItemParentId())) {
                List<InspectItemHiddenDangerDto> childrenList = inspectItemHiddendto.getChildDtoList();
                if (childrenList == null) {
                    childrenList = new ArrayList<>();
                }

                InspectItemHiddenDangerDto dto2 = new InspectItemHiddenDangerDto();
                dto2.setId(domain.getId());
                dto2.setItemName(domain.getItemName());
                dto2.setChildCount(domain.getChildCount());
                dto2.setItemCategory(domain.getItemCategory());
                dto2.setItemSubcategory(domain.getItemSubcategory());
                dto2.setStatus(domain.getStatus());
                dto2.setItemParentId(domain.getItemParentId());
                dto2.setItemOrder(domain.getItemOrder() == null ? null : domain.getItemOrder().toString());
                dto2.setItemLevel(domain.getItemLevel());

                childrenList.add(dto2);
                inspectItemHiddendto.setChildDtoList(childrenList);

                //递归
                createTreeBy(dto2, domainList);
            }
        }
    }


    /**
     * 用户负责的实验室所在的院系 和 用户负责的院系
     */
    public List<ApiUnitDto> getUserManagerLabInUnit(String userId) {

        List<UnitDomain> unitList = new ArrayList<>();
        List<String> unitIdList = new ArrayList<>();

        //用户负责的实验室所在的院系
        List<UserLaboratory> userManagerUnitList = userLaboratoryRepository.findAllByUserIdAndStatusOrderByGmtCreatedDesc(userId, CommonDbConst.DB_DELETE_NORMAL);

        for (UserLaboratory userLaboratory : userManagerUnitList) {
            if (!unitIdList.contains(userLaboratory.getManagerUnitId())) {
                if (userLaboratory.getManagerUnitId() != null) {
                    unitIdList.add(userLaboratory.getManagerUnitId());
                    //进行了排序
                    UnitDomain one = unitRepository.findByIdAndStatusOrderByUnitNameAsc(userLaboratory.getManagerUnitId(), CommonDbConst.DB_DELETE_NORMAL);
                    if (one != null) {
                        unitList.add(one);
                    }

                }

            }

        }
        List<ApiUnitDto> unitDtoList = BeanMapper.mapList(unitList, ApiUnitDto.class);


        return unitDtoList;
    }
}
